package top.mccat.filesystem.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.mccat.filesystem.anno.PassToken;
import top.mccat.filesystem.anno.UserLoginToken;
import top.mccat.filesystem.bean.Account;
import top.mccat.filesystem.exception.AccountNotFoundException;
import top.mccat.filesystem.exception.TokenNotFoundException;
import top.mccat.filesystem.mapper.AccountMapper;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author raven
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    private AccountMapper accountMapper;

    /**
     * 此方法作为一个拦截器，当执行时判断handler是否为方法，如果为方法则获取方法并查看是否存在通过验证注解，如果不存在则判断是否有需要用户权限注解
     * @param request
     * @param response
     * @param handler object对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        //如果不是映射到方法那么直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //如果有passToken注解则直接跳过认证
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getAnnotation(PassToken.class);
            if(passToken.required()){
                return true;
            }
        }
        //检查是否有需要用户权限的注解
        if(method.isAnnotationPresent(UserLoginToken.class)){
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if(userLoginToken.required()){
                String userName;
                Account account = new Account();
                //执行认证
                if(token == null){
                    Cookie[] cookies = request.getCookies();
                    if(cookies != null){
                        for(Cookie cookie : cookies){
                            if("token".equals(cookie.getName())){
                                token = cookie.getValue();
                                userName = JWT.decode(token).getAudience().get(0);
                                account.setUserName(userName);
                                //获取是否为admin，如果不为空则为admin
                                account.setIsAdmin(JWT.decode(token).getKeyId()!=null);
                                request.setAttribute("currentAccount", account);
                                if(accountMapper.selectAccount(account) == null){
                                    throw new AccountNotFoundException("账户不存在，请重新登录！");
                                }
                                return true;
                            }
                        }
                    }
                    log.debug("token为空，抛出Exception");
                    throw new TokenNotFoundException("无token，请重新登录");
                }
                //获取 token 的 user id
                //对token进行解码并获取列表下的第一条参数
                try {
                    userName = JWT.decode(token).getAudience().get(0);
                    account.setUserName(userName);
                    request.setAttribute("currentAccount", account);
                    if(accountMapper.selectAccount(account) == null){
                        throw new AccountNotFoundException("账户不存在，请重新登录！");
                    }
                } catch (JWTDecodeException e) {
                    throw new RuntimeException("401 error");
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}